package com.l024.framework.bmob;

import android.content.Context;
import android.util.Log;

import com.l024.framework.utils.CommonUtils;
import com.l024.framework.utils.Logutils;

import java.io.File;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobConfig;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
* @Author  wu_ming_zhi_bei
* @Date   2020/2/29 10:32
* @Notes  
*/
public class BmobManager {
    private static volatile BmobManager bmobManager = null;
    private final String BMOB_SDK_ID = "d82538929aa13f2e33acfe9694015f14";
    private BmobManager() {

    }

    public static BmobManager getInstance(){
        if(bmobManager==null){
            synchronized (BmobManager.class){
                if(bmobManager==null){
                    bmobManager = new BmobManager();
                }
            }
        }
        return bmobManager;
    }

    /**
     * 初始化bmob
     * @param context
     */
    public void initBmob(Context context){
        BmobConfig config =new BmobConfig.Builder(context)
        //设置appkey
        .setApplicationId(BMOB_SDK_ID)
        //请求超时时间（单位为秒）：默认15s
        .setConnectTimeout(30)
        //文件分片上传时每片的大小（单位字节），默认512*1024
        .setUploadBlockSize(1024*1024)
        //文件的过期时间(单位为秒)：默认1800s
        .setFileExpiration(2500)
        .build();
        Bmob.initialize(config);
    }

    /**
     * 判断是否登录
     */
    /**
     * 是否登录
     *
     * @return
     */
    public boolean isLogin() {
        return BmobUser.isLogin();
    }

    /**
     * 获取验证码
     */
    public void requestSMSCode(String phone, QueryListener<Integer> queryListener){
        BmobSMS.requestSMSCode(phone, "",queryListener);
    }

    /**
     * 手机号码和短信验证码登录
     */
    public void signOrLoginByMobilePhone(String phone, String code, LogInListener<BmobUser> listener){
        BmobUser.signOrLoginByMobilePhone(phone,code,listener);
    }

    /**
     * 手机+密码登录
     */
    public void loginByPhone(String phone,String password,LogInListener<BmobUser> listener){
        /**
         * 手机号码密码登录
         */
        //TODO 此处替换为你的手机号码和密码
        BmobUser.loginByAccount(phone, password,listener);
    }

    /**
     * 获取当前用户
     */
    public IMUser getUser(){
       return BmobUser.getCurrentUser(IMUser.class);
    }

    /**
     * 根据手机号查询用户
     */
    public void queryPhoneFriend(String phone,FindListener<IMUser> listener){
        baseQuery("mobilePhoneNumber", phone,listener);
//        queryLikeFriend("mobilePhoneNumber", phone,listener);
    }

    /**
     * 根据用户id查询用户
     */
    public void queryObjectIdFriend(String userId,FindListener<IMUser> listener){
        baseQuery("objectId", userId,listener);
//        queryLikeFriend("mobilePhoneNumber", phone,listener);
    }

    /**
     * 查询我的好友
     */
    public void queryMyFriends(FindListener<Friend> listener){
        BmobQuery<Friend> query = new BmobQuery<>();
        query.addWhereEqualTo("user",getUser());
        query.findObjects(listener);
    }

    /**
     * 添加我的好友
     */
    public void  addFriend(IMUser imUser, SaveListener<String> listener){
        Friend friend = new Friend();
        friend.setUser(getUser());
        friend.setFriendUser(imUser);
        friend.save(listener);
    }
    /**
     * 通过id添加我的好友
     */
    public void  addFriend(final String userId, final SaveListener<String> listener){
        queryObjectIdFriend(userId, new FindListener<IMUser>() {
            @Override
            public void done(List<IMUser> list, BmobException e) {
                if(e==null){
                    if(CommonUtils.isEmpty(list)){
                        IMUser imUser = list.get(0);
                        addFriend(imUser,listener);
                    }else{
                        Logutils.e("同意添加好友失败，没查询到该用户"+userId);
                    }
                }else{
                    Logutils.e("同意添加好友失败："+e);
                }
            }
        });
    }


    /**
     * 模糊查询
     * key：查询的类名
     *  value：模糊查询的值
     */
    public void queryLikeFriend(String key,String value,FindListener<IMUser> listener){
        BmobQuery<IMUser> query = new BmobQuery<>();
        //查询username字段的值含有“sm”的数据
        query.addWhereContains(key,value);
        query.setLimit(50);//分页查询50条
        query.findObjects(listener);
        //查询username字段的值是以“sm“字开头的数据
//        query.addWhereStartsWith("username", "sm");
//        // 查询username字段的值是以“ile“字结尾的数据
//        query.addWhereEndsWith("username", "ile");
    }

    /**
     * 查询所有用户
     */
    public void queryAllUser(FindListener<IMUser> listener){
        BmobQuery<IMUser> query = new BmobQuery<>();
        query.setLimit(50);//分页查询50条
        query.findObjects(listener);
    }

    /**
     * 查询基类
     * Key:查询字段名
     * value:值
     */
    public void baseQuery(String key,String values,FindListener listener){
        BmobQuery<IMUser> categoryBmobQuery = new BmobQuery<>();
        categoryBmobQuery.addWhereEqualTo(key, values);
        categoryBmobQuery.findObjects(listener);
    }

    /**
     * 上传头像
     */
    public void uoloadPhoto(final String nickName, File file, final OnUploadPhotoLKistener onUploadPhotoLKistener){
        /**
         * 上传文件拿到地址
         * 更新用户信息
         */
        final IMUser imUser = getUser();
        final BmobFile bmobFile = new BmobFile(file);
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    //上传成功
                    String fileUrl = bmobFile.getFileUrl();
                    imUser.setNickName(nickName);
                    imUser.setPhoto(fileUrl);
                    imUser.setTokenNickName(nickName);
                    imUser.setTokenPhoto(fileUrl);
                    //更新用户信息
                    imUser.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                onUploadPhotoLKistener.OnUpdateDone();
                            }else{
                                onUploadPhotoLKistener.OnUpdateFail(e);
                            }
                        }
                    });
                }else{
                    onUploadPhotoLKistener.OnUpdateFail(e);
                }
            }
        });
    }

    public interface OnUploadPhotoLKistener{
        public void OnUpdateDone();
        public void OnUpdateFail(BmobException e);
    }
}
